/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gestionnaire;

import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import modeles.age;

/**
 *
 * @author elo
 */
@Stateless
public class gestionnaireAge {
    
    @PersistenceContext
    private EntityManager em;

    public void creerAges() {
        if(countAges() == 0){
            creeAge("3", "age3.PNG");
            creeAge("7", "age7.PNG");
            creeAge("12", "age12.PNG");
            creeAge("16", "age16.PNG");
            creeAge("18", "age18.PNG");
            creeAge("violence", "violence.PNG");
            creeAge("bad_language", "bad_language.PNG");
            creeAge("fear", "fear.PNG");
            creeAge("sex", "sex.PNG");
            creeAge("drugs", "drugs.PNG");
            creeAge("discrimination", "discrimination.PNG");
            creeAge("gambling", "gambling.PNG");
            creeAge("online", "online.PNG");
        }
    }

    public age creeAge(String nom, String img) {
        age a = new age(nom, img);
        em.persist(a);
        return a;
    }

    public age getAgeByName(String name){
        Query q = em.createQuery("select a from age a where a.nomage like :nom");
        q.setParameter("nom", name);
        Collection<Object> result = q.getResultList();
        if(result.size() == 0)
            return null;
        else
            return (age)result.toArray()[0];
    }

    public Collection<age> getAllAges() {
        // Exécution d'une requête équivalente à un select *
        Query q = em.createQuery("select a from age a");
        return q.getResultList();
    }

    public int countAges() {
        Query q = em.createQuery("select count(a) from age a");
        int nb = Integer.parseInt(q.getSingleResult().toString());
        return nb;

    }

}
